import { defineStore } from 'pinia';
// getToken,

import { getToken, removeToken, setToken } from '@/utils/auth';

import { loginApi } from '@/api/api';
import router from '@/router';
import request from '@/utils/requests';

// state 数据可直接用this调用，但是在外部js里面则需要引入

export const useUserStore = defineStore('userStore', {
  state: () => {
    return {
      token: getToken[0],
      isRefreshing: false,
      userInfo: {
        iconUrl: '',
        userId: '',
        loginAccount: '',
        phone: '',
        email: '',
        ban: '',
        registerTime: '',
        nickname: '',
        gender: '',
        birthday: '',
        roles: []
      }
    };
  },
  getters: {},
  actions: {
    // 通过工号
    async loginByStaffNum(userInfo) {
      return new Promise((resolve, reject) => {
        request(loginApi.loginByStaffNum, userInfo)
          .then((response) => {
            const {
              data
            } = response
            this.token = data.token
            setToken(data.token, data.refreshToken, data.userId, new Date().getTime() + 28 * 60 * 1000)
            resolve()
          })
          .catch((error) => {
            console.log('loginByStaffNum', error);

            reject(error)
          })
      })
    },
    // 刷新
    async loginSessionRefresh() {
      this.isRefreshing = true
      return new Promise((resolve, reject) => {
        request(loginApi.sessionRefresh, {
          refreshToken: getToken()[1],
          userId: getToken()[2]
        })
          .then((response) => {
            const {
              data
            } = response
            this.isRefreshing = false
            setToken(data.token, data.refreshToken, data.userId, new Date().getTime() + 28 * 60 * 1000)
            router.push({
              path: this.redirect || '/'
            })
            resolve()
          })
          .catch((error) => {
            this.isRefreshing = false
            reject(error)
          })
      })
    },
    // 通过手机验证码登录
    loginByPhone({
      commit
    }, phoneLoginForm) {
      return new Promise((resolve, reject) => {
        request(loginApi.loginByPhone, {
          ...phoneLoginForm
        })
          .then((response) => {
            const {
              data
            } = response
            this.token = data.token
            setToken(data.token, data.refreshToken, data.userId, new Date().getTime() + 28 * 60 * 1000)
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    getUserInfo() {
      return new Promise((resolve, reject) => {
        request(loginApi.getInfo)
          .then((response) => {
            const { data } = response
            if (!data) {
              reject('验证失败，请重新登录')
            }
            data.roles = ['admin']
            if (!data.roles || data.roles.length <= 0) {
              reject('getInfo: 角色数据必须是一个非空数组！')
            }
            this.userInfo = data
            // debugger
            resolve(data)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 重置token
    resetToken() {
      return new Promise((resolve) => {
        removeToken() // must remove  token  first
        this.isRefreshing = false
        this.token = getToken[0]
        this.userInfo = {
          userId: '',
          iconUrl: '',
          loginAccount: '',
          phone: '',
          email: '',
          ban: '',
          registerTime: '',
          nickname: '',
          gender: '',
          birthday: '',
          roles: []
        }
        resolve()
      })
    },
    // 退出登录
    logSignOut(a) {
      // const that = this
      return new Promise((resolve, reject) => {
        request(loginApi.getInfo, { token: this.token }).then(() => {
          removeToken()
          this.resetToken()
          resolve()
        }).catch((err) => {
          reject(err)
        })
      })
    }
  }
})
export default useUserStore
